package com.example.myproject.security;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;

@Component
public class JwtTokenUtil {

    @Value("${jwt.secret}")
    private String secretStr;

    @Value("${jwt.access-token-expire}")
    private long accessExpireMillis;

    @Value("${jwt.refresh-token-expire}")
    private long refreshExpireMillis;

    private SecretKey secretKey;


    @PostConstruct
    public void init() {
        this.secretKey = Keys.hmacShaKeyFor(secretStr.getBytes(StandardCharsets.UTF_8));
    }

    // 生成访问令牌
    public String generateAccessToken(Long userId, String userName, String role, Integer userLevel) {
        Date now = new Date();
        Date expireDate = new Date(now.getTime() + accessExpireMillis);
        return Jwts.builder()
                .setSubject(userId + "")
                .claim("userID", userId)
                .claim("user_name", userName)
                .claim("role", role)
                .claim("user_level", userLevel)
                .setIssuedAt(now)
                .setExpiration(expireDate)
                .signWith(secretKey, SignatureAlgorithm.HS512)
                .compact();
    }

    // 生成刷新令牌
    public String generateRefreshToken(Long userId, String userName, String role, Integer userLevel) {
        Date now = new Date();
        Date expireDate = new Date(now.getTime() + refreshExpireMillis);
        return Jwts.builder()
                .setSubject(userId + "")
                .claim("userID", userId)
                .claim("user_name", userName)
                .claim("role", role)
                .claim("user_level", userLevel)
                .setIssuedAt(now)
                .setExpiration(expireDate)
                .signWith(secretKey, SignatureAlgorithm.HS512)
                .compact();
    }

    // 从 token 中获取用户等级
    public Integer getUserLevelFromToken(String token) {
        Claims claims = parseClaims(token);
        return claims.get("user_level", Integer.class);
    }

    // 从 token 中获取用户 ID
    public Long getUserIdFromToken(String token) {
        Claims claims = parseClaims(token);
        return Long.valueOf(claims.getSubject());
    }

    // 从 token 中获取用户角色
    public String getUserRoleFromToken(String token) {
        Claims claims = parseClaims(token);
        return claims.get("role", String.class);
    }

    // 校验 token 是否有效
    public boolean validateToken(String token) {
        try {
            parseClaims(token);
            return true;
        } catch (JwtException | IllegalArgumentException e) {
            return false;
        }
    }

    public Claims parseClaims(String token) {
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(token)
                .getBody();
    }
}